package com.gxitsky.async.design.task;

import com.gxitsky.utils.JSON;

import javax.servlet.AsyncContext;
import javax.servlet.ServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;

/**
 * @desc 任务
 * @author gxing
 * @date 2022/7/28 17:02
 */
public class Work implements Runnable {

    private AsyncContext asyncContext;

    public Work(AsyncContext asyncContext) {
        this.asyncContext = asyncContext;
    }

    @Override
    public void run() {
        System.out.println("异步线程启动:" + Thread.currentThread().getName());
        try {
            ServletResponse response = asyncContext.getResponse();
            response.setContentType("application/json;charset=UTF-8");
            PrintWriter writer = response.getWriter();
            HashMap<String, Object> map = new HashMap<>();
            map.put("id", 100L);
            map.put("message","Hello World!");
            writer.println(JSON.toJsonString(map));
        } catch (IOException e) {
            e.printStackTrace();
        }
        asyncContext.complete();
        System.out.println("异步线程结束");
    }
}